package com.notary.aspect;


import com.notary.entity.vo.JsonResult;
import com.notary.exception.BusinessException;
import com.notary.exception.code.BusinessExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.List;


/**
 * @author Administrator
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理token过期
     *
     * @param exception
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BusinessException.class)
    public JsonResult ExceptionHandler(BusinessException exception) {
        log.info(exception.getMessage(), exception);
        return JsonResult.fail(BusinessExceptionCode.TOKEN_EXPIRED);
    }


    /**
     * 处理对象属性不满足校验规则异常信息
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JsonResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        final List<FieldError> fieldErrors = result.getFieldErrors();
        StringBuilder builder = new StringBuilder();

        for (FieldError error : fieldErrors) {
            builder.append(error.getDefaultMessage() + "\n");
        }
        return JsonResult.fail("-1", builder.toString());
    }


    /**
     * 处理请求单个参数不满足校验规则的异常信息
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public JsonResult constraintViolationExceptionHandler(ConstraintViolationException exception) {
        log.error(exception.getMessage());
        return JsonResult.fail("-1", exception.getMessage());
    }


    /**
     * 处理未定义的其他异常信息
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler(Exception exception) {
        log.error(exception.getMessage(), exception);
        return JsonResult.fail("-1", exception.getMessage());
    }


    @ExceptionHandler(value = {NoHandlerFoundException.class})
    public JsonResult noHandlerFoundException(HttpServletRequest request, Exception e) {
        log.error(e.getMessage(), e);
        return JsonResult.fail("-1", e.getMessage());
    }
}
